// API路由
const express = require("express");
const router = express.Router();
const cozeApi = require("../services/cozeApi");

// 获取今日古诗
router.get("/daily-poem", async (req, res) => {
	try {
		const { keyword, tags, writer } = req.query;
		const result = await cozeApi.getDailyPoem({ keyword, tags, writer });

		if (result.success) {
			// 格式化数据
			const poemData = result.data;

			// 处理内容，将字符串分割为数组
			let content = [];
			if (poemData.content) {
				// 尝试根据标点符号拆分诗句
				content = poemData.content
					.split(/[，。？！,\.?!]/)
					.filter((line) => line.trim());
			}

			// 创建注释数组
			let notes = [];
			if (poemData.annotation) {
				// 简单处理注释，这里只是示例，实际可能需要更复杂的解析
				const annotationParts = poemData.annotation.split("。");
				for (let part of annotationParts) {
					if (part.includes("：")) {
						const [key, value] = part.split("：");
						if (key && value) {
							notes.push({ key: key.trim(), value: value.trim() });
						}
					}
				}
			}

			// 获取插图
			let illustration = null;
			if (poemData.content) {
				try {
					const illustrationResult = await cozeApi.getPoemIllustration(
						poemData.content
					);
					if (illustrationResult.success && illustrationResult.data) {
						illustration = {
							imageUrl:
								illustrationResult.data.imageUrl &&
								illustrationResult.data.imageUrl[0],
							description: illustrationResult.data.description,
						};
					}
				} catch (error) {
					console.error("获取插图失败:", error);
				}
			}

			res.json({
				success: true,
				data: {
					title: poemData.title || "",
					author: poemData.author || "",
					dynasty: poemData.dynasty || "",
					content: content,
					type: "古诗",
					notes: notes,
					appreciation: poemData.introduce || "",
					imageUrl: illustration ? illustration.imageUrl : "",
					description: illustration ? illustration.description : "",
				},
			});
		} else {
			res.status(500).json({
				success: false,
				message: result.error || "获取古诗失败",
			});
		}
	} catch (error) {
		console.error("API错误:", error);
		res.status(500).json({
			success: false,
			message: "服务器内部错误",
		});
	}
});

// 搜索古诗
router.get("/search-poems", async (req, res) => {
	try {
		const { keyword, tags, writer } = req.query;
		const result = await cozeApi.searchPoems({ keyword, tags, writer });

		if (result.success) {
			const poems = result.data.poems || [];

			// 格式化搜索结果
			const formattedPoems = poems.map((poem) => {
				// 处理诗句内容，拆分为数组
				let content = [];
				if (poem.content) {
					content = poem.content
						.split(/[，。？！,\.?!]/)
						.filter((line) => line.trim());
				}

				// 处理注释
				let notes = [];
				if (poem.annotation) {
					const annotationParts = poem.annotation.split("。");
					for (let part of annotationParts) {
						if (part.includes("：")) {
							const [key, value] = part.split("：");
							if (key && value) {
								notes.push({ key: key.trim(), value: value.trim() });
							}
						}
					}
				}

				return {
					title: poem.title || "",
					dynasty: poem.dynasty || "",
					author: poem.writer || "",
					content: poem.content || "",
					contentArray: content,
					notes: notes,
					appreciation: poem.appreciation || "",
				};
			});

			res.json({
				success: true,
				data: formattedPoems,
			});
		} else {
			res.status(500).json({
				success: false,
				message: result.error || "搜索古诗失败",
			});
		}
	} catch (error) {
		console.error("API错误:", error);
		res.status(500).json({
			success: false,
			message: "服务器内部错误",
		});
	}
});

// 获取古诗插图
router.post("/poem-illustration", async (req, res) => {
	try {
		const { poem } = req.body;

		if (!poem) {
			return res.status(400).json({
				success: false,
				message: "缺少必要参数: poem",
			});
		}

		const result = await cozeApi.getPoemIllustration(poem);

		if (result.success) {
			res.json({
				success: true,
				data: {
					imageUrl: result.data.imageUrl && result.data.imageUrl[0],
					description: result.data.description,
				},
			});
		} else {
			res.status(500).json({
				success: false,
				message: result.error || "获取古诗插图失败",
			});
		}
	} catch (error) {
		console.error("API错误:", error);
		res.status(500).json({
			success: false,
			message: "服务器内部错误",
		});
	}
});

module.exports = router;
